package com.yksj.healthtalk.ui.friend;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.core.ImageLoader;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.yksj.healthtalk.adapter.InterestAdapter;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.CommonExplainActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.SearchByTagActivity;
import com.yksj.healthtalk.comm.ZoomImgeDialogFragment;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.entity.TagEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.salon.SalonAboutOthersActivity;
import com.yksj.healthtalk.ui.views.TagsGridView;
import com.yksj.healthtalk.utils.CollectUtils;
import com.yksj.healthtalk.utils.DataParseUtil;
import com.yksj.healthtalk.utils.DialogUtils;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.HStringUtil;
import com.yksj.healthtalk.utils.PersonInfoUtil;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.ViewUtils;

public class FriendInformUI extends BaseFragmentActivity implements
		OnClickListener, OnItemClickListener {

	private CustomerInfoEntity mInfoEntity;
	private TextView lahei_text;// 是否拉黑的Textview
	private TextView lahei_text_40;// 是否拉黑的Textview
	private AppData mAppData;
	private ImageLoader mImageLoader;
	private InterestAdapter mAdapterXingQu;
	private List<TagEntity> xingQuAdapterList;// 个性签名喜好标签
	private List<TagEntity> bodyAdapterList;// 获取的关注身体标签
	private final int DIALOG_QUERY = 002;
	private final int DIALOG_REPORT = 003;
	private final int DIALOG_HANDLE = 004;
	private PopupWindow mPopBottom;
	private CustomerInfoEntity cacheCustomerInfoEntity;
	private TextView mChattingTv;
	private TextView mChattingTv_40;
	private String qrCode;
	private String type;;// 0-社交场  1-医生馆

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			LodingFragmentDialog.dismiss(getSupportFragmentManager());
			String result = intent.getStringExtra("result");
			if (result.equals("-1")) {
				ToastUtil.showShort(FriendInformUI.this,R.string.against__blacklist_operations);
			} else if (result.equals("0")) {
				ToastUtil.showShort(FriendInformUI.this,R.string.groupNewFail);
				return;
			} else {
				FriendHttpUtil.requestAttentionTofriendsResult(FriendInformUI.this, cacheCustomerInfoEntity,
						mAppData);
				switch (cacheCustomerInfoEntity.getAttentionFriendFlag()) {
				case 7:
				case 5:// 取消客户收藏成功
				case 0:// 取消关注成功
					collect.setVisibility(View.VISIBLE);
					collect_40.setVisibility(View.VISIBLE);
					notCollect.setVisibility(View.GONE);
					notCollect_40.setVisibility(View.GONE);
					break;
				case 6:
				case 4:// 客户收藏成功
				case 1:// 关注成功
					collect.setVisibility(View.GONE);
					notCollect.setVisibility(View.VISIBLE);
					collect_40.setVisibility(View.GONE);
					notCollect_40.setVisibility(View.VISIBLE);
					break;
				case 2:// 加入黑名单成功
					lahei_text.setText("取消拉黑");
					lahei_text_40.setText("取消拉黑");
					laheiTextImage.setBackgroundResource(R.drawable.person_quxiao_lahei);
					laheiTextImage_40.setBackgroundResource(R.drawable.person_quxiao_lahei);
					collect.setVisibility(View.VISIBLE);
					notCollect.setVisibility(View.GONE);
					collect_40.setVisibility(View.VISIBLE);
					notCollect_40.setVisibility(View.GONE);
					break;
				case 3:// 取消黑名单成功
					lahei_text.setText(" 拉黑 ");
					laheiTextImage.setBackgroundResource(R.drawable.person_lahei);
					laheiTextImage_40.setBackgroundResource(R.drawable.person_lahei);
					break;
				}
				if(mInfoEntity.getIsAttentionFriend()!=0){//有关系的时候 出现编辑按钮和右上角
					mRemarks.setVisibility(View.VISIBLE);
				}else{
					mRemarks.setVisibility(View.GONE);
				}
			}
		}
	};
	private View laheiTextImage;// 是否拉黑的图标
	private View laheiTextImage_40;// 是否拉黑的图标
	private View collect;
	private View collect_40;
	private View notCollect;
	private View notCollect_40;
	private EditText mRemarks;//备注

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_info);
		initView();
		Intent intent =  getIntent();
		if (intent.hasExtra("id")) {
			initData(type,qrCode,intent.getStringExtra("id"));
		} else if(intent.hasExtra("qrCode")){
			initData(intent.getStringExtra("type"),intent.getStringExtra("qrCode"),"");
		}else{
			mInfoEntity = getIntent().getParcelableExtra("PersonInfo");
			inidatata();
		}
		
	}

	private void inidatata() {
		mImageLoader = ImageLoader.getInstance();
		mAppData = HTalkApplication.getAppData();
		setUpView();
		ScrollView scrollView= (ScrollView)findViewById(R.id.scrollvie);
		scrollView.scrollTo(0,0);
		scrollView.smoothScrollTo(0, 0);
		titleTextV.setText(mInfoEntity.getNickName());
		
		mRemarks=(EditText)findViewById(R.id.remarks);
		mRemarks.setOnClickListener(this);
		if(mInfoEntity.getIsAttentionFriend()!=0){//有关系的时候 出现编辑按钮和右上角
			mRemarks.setVisibility(View.VISIBLE);
		}else{
			mRemarks.setVisibility(View.GONE);
		}
		if(!"".equals(mInfoEntity.getRemarkName()))
		mRemarks.setText(mInfoEntity.getRemarkName());
		
		if(mInfoEntity.isDoctor()){
			findViewById(R.id.friend_bottom_view).setVisibility(View.GONE);
		}
	}

	private void initData(String type , String qrCode ,String id) {
		HttpRestClient.doHttpFindCustomerInfoByCustId(type,qrCode,id,SmartFoxClient.getLoginUserId(),
				new ObjectHttpResponseHandler(this) {
					@Override
					public CustomerInfoEntity onParseResponse(String content) {
						CustomerInfoEntity entity = null;
						if (TextUtils.isEmpty(content) && content.equalsIgnoreCase("N")) {
							ToastUtil.showShort(getApplicationContext(),R.string.request_error);
						} else {
							try {
								entity = DataParseUtil.jsonToCustmerInfo(new JSONObject(content));
							} catch (JSONException e) {
							}
						}
						return entity;
					}
					@Override
					public void onSuccess(int statusCode, Object response) {
						if (response != null) {
							mInfoEntity = (CustomerInfoEntity) response;
							inidatata();
						}else {
							setResult(RESULT_OK,getIntent());
							finish();
						}
					}
				});

	}

	@Override
	protected void onResume() {
		IntentFilter filter = new IntentFilter(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(CollectUtils.ACTION_FRIEND_INFO);
		registerReceiver(receiver, filter);
		super.onResume();
	}

	@Override
	protected void onPause() {
		unregisterReceiver(receiver);
		super.onPause();
	}
	@Override
	protected void onStop() {
		super.onStop();
		if (mPopBottom != null && mPopBottom.isShowing()) {
			mPopBottom.dismiss();
			mPopBottom = null;
		}
	}

	/**
	 * 初始化控件,并赋值
	 */
	private void setUpView() {
		collect = findViewById(R.id.info_collect);
		collect_40 = findViewById(R.id.info_collect_40);
		notCollect = findViewById(R.id.delete);
		notCollect_40 = findViewById(R.id.delete_40);
		findViewById(R.id.info_inform).setOnClickListener(this);
		collect.setOnClickListener(this);
		collect_40.setOnClickListener(this);
		findViewById(R.id.info_dialog).setOnClickListener(this);
		findViewById(R.id.info_dialog_40).setOnClickListener(this);
		findViewById(R.id.info_lahei).setOnClickListener(this);
		findViewById(R.id.info_lahei_40).setOnClickListener(this);
		lahei_text = (TextView) findViewById(R.id.lahei_text);
		lahei_text_40 = (TextView) findViewById(R.id.lahei_text_40);
		notCollect.setOnClickListener(this);
		notCollect_40.setOnClickListener(this);
		mChattingTv = (TextView) findViewById(R.id.isDoctorFlage);
		mChattingTv_40 = (TextView) findViewById(R.id.isDoctorFlage_40);
		laheiTextImage = findViewById(R.id.lahei_text_image);
		laheiTextImage_40 = findViewById(R.id.lahei_text_image_40);
		lahei_text.setText(" 拉黑 ");
		lahei_text_40.setText(" 拉黑 ");
		laheiTextImage.setBackgroundResource(R.drawable.person_lahei);
		laheiTextImage_40.setBackgroundResource(R.drawable.person_lahei);
		
		if(!SmartFoxClient.getLoginUserInfo().isDoctor()){
			ViewUtils.setGone(findViewById(R.id.btn_lay), false);
		}else{
			ViewUtils.setGone(findViewById(R.id.btn_lay_40), false);
		}
		
		if (mInfoEntity.getIsAttentionFriend() == 0) {// 客户关系标记 0-无关系
			collect.setVisibility(View.VISIBLE);
			collect_40.setVisibility(View.VISIBLE);
			notCollect.setVisibility(View.GONE);
			notCollect_40.setVisibility(View.GONE);
		} else if (mInfoEntity.getIsAttentionFriend() == 1) {// 1-我关注
			collect.setVisibility(View.GONE);
			notCollect.setVisibility(View.VISIBLE);
			collect_40.setVisibility(View.GONE);
			notCollect_40.setVisibility(View.VISIBLE);
		} else if (2 == mInfoEntity.getIsAttentionFriend()) {// 2-黑名单
			lahei_text.setText("取消拉黑");
			lahei_text_40.setText("取消拉黑");
			laheiTextImage.setBackgroundResource(R.drawable.person_quxiao_lahei);
			laheiTextImage_40.setBackgroundResource(R.drawable.person_quxiao_lahei);
		} else if (3 == mInfoEntity.getIsAttentionFriend() || mInfoEntity.getIsAttentionFriend() == 4) {//客户
			collect.setVisibility(View.GONE);
			notCollect.setVisibility(View.VISIBLE);
			collect_40.setVisibility(View.GONE);
			notCollect_40.setVisibility(View.VISIBLE);
		}
		mChattingTv.setText(PersonInfoUtil.getTalkName(mInfoEntity.isDoctor()));
		mChattingTv_40.setText(PersonInfoUtil.getTalkName(mInfoEntity.isDoctor()));
		
		TextView customerDataName = (TextView) findViewById(R.id.customer_data_name);
		customerDataName.setText(mInfoEntity.getNickName());
		TextView customerDescription = (TextView) findViewById(R.id.customer_data_add);
		customerDescription.setText(mInfoEntity.getDescription());
		TextView accountTv = (TextView) findViewById(R.id.info_account);
		accountTv.setText(mInfoEntity.getUsername());
		TextView moneyTv = (TextView) findViewById(R.id.info_money);
		moneyTv.setText(String.valueOf(mInfoEntity.getMoney()));
		ImageView headImage = (ImageView) findViewById(R.id.info_head);
		headImage.setOnClickListener(this);
		mImageLoader.displayImage(mInfoEntity.getSex(),mInfoEntity.getNormalHeadIcon(), headImage);

		TextView birTv = (TextView) findViewById(R.id.info_birthday);
		birTv.setText(mInfoEntity.getBirthday());

		TextView locaTv = (TextView) findViewById(R.id.info_location);
		locaTv.setText(mInfoEntity.getDwellingplace());

		TextView sexName = (TextView) findViewById(R.id.info_xingbie);
		 if("1".equals(mInfoEntity.getSex())){
			sexName.setText("男");
		}else if("2".equals(mInfoEntity.getSex())){
			sexName.setText("女");
		}else{
			sexName.setText("保密");
		}
		
		TextView hunyinTv = (TextView) findViewById(R.id.info_hunyin);
		hunyinTv.setText(mInfoEntity.getHunyin());

		TextView xueliTv = (TextView) findViewById(R.id.info_xueli);
		xueliTv.setText(mInfoEntity.getCultureLevel());

		TextView zhiyeTv = (TextView) findViewById(R.id.info_zhiye);
		zhiyeTv.setText(mInfoEntity.getMetier());

		TagsGridView mGridViewXingQu = (TagsGridView) findViewById(R.id.xingqu);
		bodyAdapterList = DataParseUtil.JsonToListEntity(mInfoEntity.getSameExperience(), 1);
		TagsGridView mBodyBiaoQian = (TagsGridView) findViewById(R.id.bodybiaoqian);
		mBodyBiaoQian.setAdapter(new InterestAdapter(this, bodyAdapterList,R.layout.textiterm));

		xingQuAdapterList = DataParseUtil.JsonToListEntity(mInfoEntity.getAttention(), 0);
		mAdapterXingQu = new InterestAdapter(this, xingQuAdapterList,R.layout.textiterm);
		mGridViewXingQu.setAdapter(mAdapterXingQu);
		mBodyBiaoQian.setOnItemClickListener(this);
		mGridViewXingQu.setOnItemClickListener(this);
		if (mInfoEntity.isShow() || mInfoEntity.isAudit()) {//如果是医生
			findViewById(R.id.btn_lay).setVisibility(View.GONE);
		}
	}

	/**
	 * 初始化title
	 */
	private void initView() {
		initTitle();
		titleLeftBtn.setOnClickListener(this);
		
//		findViewById(R.id.title_back).setOnClickListener(this);
//		titleName = (TextView) findViewById(R.id.title_lable);
//		Button mTitleRight = (Button) findViewById(R.id.title_right);
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn2.setBackgroundResource(R.drawable.icon_more);
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.info_inform:// 举报
			if (!SystemUtils.isNetWorkValid(this)) {
				ToastUtil.showBasicShortToast(this, "请检查网络是否可用...");
				return;
			}else{
//				intent=new Intent(this, UserReportActivity.class);
//				intent.putExtra("id", mInfoEntity.getId());
//				startActivity(intent);	
				intent=new Intent(this, CommonExplainActivity.class);
				intent.putExtra("title", "投诉");  
				intent.putExtra("mContentCount", 70);  //字数限制  默认是200
				intent.putExtra("content", "");  //内容
				startActivityForResult(intent, 10000);
			}
			break;
		case R.id.info_collect:// 关注
		case R.id.info_collect_40:// 关注
			cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(
					this,  null, mInfoEntity);
			break;
		case R.id.info_dialog:// 对话页面
		case R.id.info_dialog_40:// 对话页面
			FriendHttpUtil.onItemClick(this, mInfoEntity);
			break;
		case R.id.delete:// 取消关注
		case R.id.delete_40:// 取消关注
			if (!SystemUtils.isNetWorkValid(this)) {
				ToastUtil.showBasicShortToast(this, "请检查网络是否可用...");
				return;
			}
			cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(this, null, mInfoEntity);
			break;
		case R.id.info_lahei:// 拉黑or取消拉黑
		case R.id.info_lahei_40:// 拉黑or取消拉黑
			if (!SystemUtils.isNetWorkValid(this)) {
				ToastUtil.showBasicShortToast(this, "请检查网络是否可用...");
				return;
			}
			cacheCustomerInfoEntity = FriendHttpUtil.requestAttentionTofriends(this, true, mInfoEntity);
			break;
		case R.id.info_head:// 放大头像
			if (!SystemUtils.isNetWorkValid(this)) {
				ToastUtil.showBasicShortToast(this, "请检查网络是否可用...");
				return;
			}
			if (!TextUtils.isEmpty(mInfoEntity.getBigHeadIcon())) {
				ZoomImgeDialogFragment.show(mInfoEntity.getBigHeadIcon(),getSupportFragmentManager());
			}
			break;
		case R.id.title_right2:
			showMenu(v);
			break;
		case R.id.salon_add:// 他的沙龙
			Intent intent2 = new Intent();
			intent2.setClass(this, SalonAboutOthersActivity.class);
			intent2.putExtra("mInfoEntity", mInfoEntity);
			startActivity(intent2);
			break;
		case R.id.question_online:// 他的问题
			
			break;
		case R.id.you_sheying:// 他的摄影
//			intent = new Intent(FriendInformUI.this, MyPhotoGallery.class);
//			intent.putExtra("cusid", mInfoEntity.getId());
//			startActivity(intent);
			break;
		case R.id.remarks://修改备注
			intent=new Intent(this,FriendRemark.class);
			intent.putExtra("id", mInfoEntity.getId());
			intent.putExtra("remark",mRemarks.getText().toString()); //以前的备注
			startActivityForResult(intent, 3000);
			break;
		}
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode!=RESULT_OK||data==null)return;
		switch (requestCode) {
		case 3000:
			String remarkString=data.getStringExtra("remark");
			mRemarks.setText(remarkString);
			break;
		case 10000://投诉建议
			String content = data.getStringExtra("content");
			if(!HStringUtil.isEmpty(content)){
				SmartFoxClient.report(mInfoEntity.getId(),content);
				ToastUtil.showToastPanl("提交成功");
			}
		}
	}

	private void showMenu(View view) {
		if (mPopBottom == null) {
			LayoutInflater inflater = LayoutInflater.from(this);
			View v = inflater.inflate(R.layout.friend_pop_top, null);
			mPopBottom = new PopupWindow(v, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, true);
			mPopBottom.setBackgroundDrawable(new BitmapDrawable());
			mPopBottom.setFocusable(true);
			RadioGroup radioGroup = (RadioGroup) v.findViewById(R.id.radiogroup);
			int count = radioGroup.getChildCount();
			for (int i = 0; i < count; i++) {
				radioGroup.getChildAt(i).setOnClickListener(this);
			}
		} else if (mPopBottom.isShowing()) {
			mPopBottom.dismiss();
			return;
		}
		mPopBottom.showAsDropDown(view);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_QUERY:
			return DialogUtils.getLoadingDialog(this,
					getString(R.string.onQuery));
		case DIALOG_REPORT:
			return DialogUtils.showNotifyDialog(this, R.string.reportNotify,
					this);
		case DIALOG_HANDLE:
			return DialogUtils.getLoadingDialog(this,
					getString(R.string.onHandler));
		default:
			return DialogUtils.getLoadingDialog(this,
					getString(R.string.onEditor));
		}
	}

	/**
	 * 跳转到对话界面
	 */
	private void startChatting(String message) {
		
		FriendHttpUtil.onItemClick(this, mInfoEntity);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		CustomerInfoEntity entity = new CustomerInfoEntity();
		entity.setId(SmartFoxClient.getSmartFoxClient().getUserId());
		Intent intent;
		switch (arg0.getId()) {
		case R.id.xingqu:
			entity.setType(0);
			entity.setInterestName(xingQuAdapterList.get(arg2).getName());
			entity.setInterestCode(xingQuAdapterList.get(arg2).getId());
			break;
		case R.id.bodybiaoqian:
			entity.setType(2);
			entity.setSameExperienceCode(Integer.valueOf(bodyAdapterList.get(arg2).getId()));
			entity.setSameExperience(bodyAdapterList.get(arg2).getName());
			break;
		}
		intent = new Intent(this, SearchByTagActivity.class);
		intent.putExtra("entity", entity);
		startActivity(intent);

	}

	@Override
	public void onBackPressed() {
		// 从好友列表除"我的" 进入资料 返回需要刷新列表
		if (getIntent().hasExtra("positon")) {
			Intent i = getIntent();
			i.putExtra("mFriendInformUI", mInfoEntity);
			i.putExtra("position", getIntent().getExtras().getInt("positon"));
			this.setResult(0, i);
		}
		super.onBackPressed();
	}
	
	
	/**
	 * 得到当前时间
	 * @return
	 */
	public static Long getDateTime(){
		SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMMddHHmmss");
		Calendar c = Calendar.getInstance();

		try {
			c.setTime(new SimpleDateFormat("yyyyMMddHHmmss").parse(myFormatter.format(new Date())));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c.getTimeInMillis();
	}
	

}
